<template>
  <div class="chat">
    <van-sticky :offset-top="0">
      <!--1. 搜索-->
      <div class="top_wrap">
        <div class="nav"
          v-if="state.chatUserPro[0]">
          <van-icon name="arrow-left"
            color="#fff"
            size="16px"
            @click="backHnadler" />
          <div class="company-name">
            {{
            state.chatUserPro[0]?(state.chatUserPro[0].nick!==''
            ?state.chatUserPro[0].nick:props.companyInfo
            ?props.companyInfo.title:''):""
            }}
          </div>
          <!-- <div class="company-name">{{props.companyInfo ? props.companyInfo.title:msg.userProfile.nick}}</div> -->
        </div>
      </div>
    </van-sticky>
    <div class="scroll-wrap"
      ref="scrollWrap">

      <div class="company-card">
        <div class="card-box">

          <div class="card-top ">
            <div class="header">
              <div class="title">高级交互设计师</div>
              <div class="salary">10~20k/月</div>
            </div>
            <div class="tag">北京|5-10年|本科</div>
            <!-- <div class="tag">{{work.workAddress}}|{{work.workRange}}|{{work.education}}</div> -->
            <div class="welfare">
              <!-- <span v-for="(welfare,index) in work.welfare"
          :key="index">{{welfare}}</span> -->
              <span>全职</span>
            </div>
          </div>
          <div class="card-bottom">
            <div class="chat-time">
              8月8日 13:29向你发起沟通
            </div>
          </div>
        </div>
      </div>

      <div class="chat-wrap">
        <ul>
          <li v-for="(msg,index) in state.messageList"
            :key="msg.ID">
            <div :class="[msg.flow==='out'?'right-message':'left-message']">
              <img :src="[msg.flow==='out'? '': (props.companyInfo?props.companyInfo.logoUrl : msg.avatar)]"
                alt="">
              <div class="text">
                {{msg.payload.text}}
              </div>
            </div>
          </li>

        </ul>
      </div>
    </div>

    <div class="input-wrap">
      <input type="text"
        class="send-text"
        placeholder="请输入..."
        v-model="sendText">
      <div class="send-btn"
        @click="send">发送</div>
    </div>

  </div>
</template>

<script setup lang="ts">
  // const props = defineProps({
  //   }
  // })
  import { useStore } from 'vuex'
  import { reactive, getCurrentInstance, ref, nextTick, onMounted } from 'vue'
  const { proxy } = getCurrentInstance()
  const store = useStore()
  const props = defineProps({
    companyInfo: {
      type: Object
    },
    cvId: {
      type: String
    }
  })
  // 滚动容器到聊天最底部
  let scrollWrap = ref(null)
  let state = reactive({
    messageList: [],
    chatUserPro: []
  })
  // 发送的文本
  let sendText = ref('')
  //关闭窗口
  const emit = defineEmits(['backHnadler'])
  const backHnadler = () => {
    emit('update:closeChat')
  }

  // 消息的发送
  const send = () => {
    console.log(sendText.value)

    if (sendText.value.trim() == '') {
      console.log('不能发空消息')
      return
    }
    let message = proxy.tim.createTextMessage({
      to: props.companyInfo ? props.companyInfo._id : props.cvId,
      conversationType: proxy.TIM.TYPES.CONV_C2C,
      // 消息优先级，用于群聊（v2.4.2起支持）。如果某个群的消息超过了频率限制，后台会优先下发高优先级的消息，详细请参考：https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6)
      // 支持的枚举值：TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL（默认）, TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
      // priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
      payload: {
        text: sendText.value
      },
      // v2.20.0起支持C2C消息已读回执功能，如果您发消息需要已读回执，需购买旗舰版套餐，并且创建消息时将 needReadReceipt 设置为 true
      needReadReceipt: true
      // 消息自定义数据（云端保存，会发送到对端，程序卸载重装后还能拉取到，v2.10.2起支持）
      // cloudCustomData: 'your cloud custom data'
    })
    // 2. 发送消息
    let promise = proxy.tim.sendMessage(message)
    promise
      .then(function (imResponse) {
        // 发送成功
        console.log(imResponse)
        state.messageList.push(imResponse.data.message)
      })
      .catch(function (imError) {
        // 发送失败
        console.warn('sendMessage error:', imError)
      })
  }

  //接收消息
  onMounted(() => {
    let onMessageReceived = function (event) {
      // event.data - 存储 Message 对象的数组 - [Message]
      console.log(event.data)
      state.messageList.push(...event.data)
    }
    proxy.tim.on(proxy.TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived)
    //第一次拉取历史消息
    let promise = proxy.tim.getMessageList({ conversationID: `C2C${props.companyInfo ? props.companyInfo._id : props.cvId}`, count: 15 })
    promise.then(function (imResponse) {
      const messageList = imResponse.data.messageList // 消息列表。
      const nextReqMessageID = imResponse.data.nextReqMessageID // 用于续拉，分页续拉时需传入该字段。
      const isCompleted = imResponse.data.isCompleted // 表示是否已经拉完所有消息。
      console.log(messageList)
      state.messageList = messageList

      nextTick(() => {
        let scrollHeight = scrollWrap.value.scrollHeight
        console.log(scrollHeight)
        scrollWrap.value.scrollTop = scrollHeight
      })

      let getUserProfile = proxy.tim.getUserProfile({
        userIDList: [props.companyInfo ? props.companyInfo._id : props.cvId] // 请注意：即使只拉取一个用户的资料，也需要用数组类型，例如：userIDList: ['user1']
      })
      getUserProfile
        .then(function (imRes) {
          console.log(imRes.data) // 存储用户资料的数组 - [Profile]
          state.chatUserPro = imRes.data
        })
        .catch(function (imError) {
          console.warn('getUserProfile error:', imError) // 获取其他用户资料失败的相关信息
        })
    })
  })
  // 这里会不停的触发
  // 第三个参数是改变第二个参数的函数this指向,因为该this指向的是被调用者的身上,我们需要获取到当前组件的实例,我们要遍历
</script>

<style lang="less" scoped>
@mainColor: #149639;
.chat {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;
  background: #f4f4f4;
  width: 100vw;
  height: 100vh;
  // padding-bottom: 20px;
  overflow: auto;
  .top_wrap {
    height: 75px;
    padding: 40px 0 0 0;
    background: linear-gradient(to right, #6db260, #3da632);

    .nav {
      padding: 0 13px;
      height: 25px;
      display: flex;

      align-items: center;
      .company-name {
        flex: 1;
        text-align: center;
        font-size: 20px;
        color: #fff;
      }
    }
  }
  .scroll-wrap {
    overflow: auto;
    height: calc(100vh - 75px);
    padding-bottom: 70px;
    .company-card {
      margin-top: 15px;
      padding: 0 13px;
      .card-box {
        background: #fff;
        border-radius: 12px;
        padding: 0 13px;
        box-shadow: 0 0 10px -5px #149639;
        .card-top {
          // display: flex;
          padding: 14px 0 18px 0;
          border-bottom: 1px solid #f4f4f4;
          .header {
            display: flex;
            justify-content: space-between;
            height: 20px;
            .title {
              font-size: 20px;
            }
            .salary {
              font-size: 15px;
              font-weight: 600;
              color: @mainColor;
            }
          }
          .tag {
            margin-top: 10px;
            font-size: 12px;
            color: #898989;
          }
          .welfare {
            margin-top: 10px;
            span {
              display: inline-block;
              background: #f4f4f4;
              color: #b7b7b7;
              // width: 35px;
              padding: 0 5px;
              height: 20px;
              line-height: 20px;
              text-align: center;
              border-radius: 5px;
              margin-right: 5px;
            }
          }
        }
        .card-bottom {
          .chat-time {
            padding: 15px 0;
          }
        }
      }
    }
    .chat-wrap {
      padding: 13px;
      > ul {
        margin-top: 10px;
        li {
          padding: 15px 0;
          .left-message,
          .right-message {
            display: flex;
            img {
              width: 35px;
              height: 35px;
            }
            .text {
              line-height: 1.5;
              display: flex;
              flex-wrap: wrap;
              word-break: break-word;
              align-items: center;
              background: #fff;
              border-radius: 5px;
              color: #3d3d3d;
              margin-left: 10px;
              max-width: 175px;
              font-size: 15px;
              padding: 5px 8px;
            }
          }
          .right-message {
            display: flex;
            flex-direction: row-reverse;
            .text {
              background: #149639;
              color: #f4f4f4;
              margin-right: 10px;
            }
          }
        }
      }
    }
  }

  .input-wrap {
    position: absolute;
    bottom: 0;
    right: 0;
    left: 0;
    padding: 9px 13px;
    border-top: 1px solid #f3f3f3;
    height: 48px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;
    background: #fff;
    .send-text {
      border-radius: 20px;
      padding: 10px;
      flex: 1;
      border: none;
      background: #f4f4f4;
    }
    .send-btn {
      padding: 0 5px;
      font-size: 15px;
      color: #149639;
    }
  }
}
</style>